package com.student.enrollment.controller;

import com.student.common.entity.Result;
import com.student.common.entity.Enrollment;
import com.student.enrollment.service.EnrollmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 选课控制器
 * 
 * @author student
 * @date 2025
 */
@RestController
@RequestMapping("/enrollment")
public class EnrollmentController {
    
    @Autowired
    private EnrollmentService enrollmentService;
    
    /**
     * 学生选课
     */
    @PostMapping("/select")
    public Result<String> selectCourse(@RequestParam String studentId, 
                                    @RequestParam String courseId,
                                    @RequestParam String semester,
                                    @RequestParam(required = false) String enrollmentDate,
                                    HttpServletRequest request) {
        try {
            // 获取当前用户信息
            String role = (String) request.getAttribute("role");
            String relatedId = (String) request.getAttribute("relatedId");
            
            System.out.println("选课请求 - 角色: " + role + ", 关联ID: " + relatedId + ", 学号: " + studentId);
            
            // 学生角色只能为自己选课
            if ("学生".equals(role) || "STUDENT".equals(role)) {
                if (!studentId.equals(relatedId)) {
                    System.out.println("权限检查失败 - 学号不匹配: " + studentId + " != " + relatedId);
                    return Result.error("权限不足，只能为自己选课");
                }
            }
            
            System.out.println("开始选课 - 学号: " + studentId + ", 课程: " + courseId + ", 学期: " + semester + ", 选课时间: " + enrollmentDate);
            boolean success = enrollmentService.selectCourse(studentId, courseId, semester, enrollmentDate);
            if (success) {
                System.out.println("选课成功");
                return Result.success("选课成功");
            } else {
                System.out.println("选课失败 - 可能已选择该课程");
                return Result.error("选课失败，您已经选择了该课程");
            }
        } catch (Exception e) {
            System.err.println("选课异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("选课失败：" + e.getMessage());
        }
    }
    
    /**
     * 学生退课
     */
    @PostMapping("/drop")
    public Result<String> dropCourse(@RequestParam String studentId, 
                                 @RequestParam String courseId,
                                 @RequestParam String semester,
                                 HttpServletRequest request) {
        try {
            // 获取当前用户信息
            String role = (String) request.getAttribute("role");
            String relatedId = (String) request.getAttribute("relatedId");
            
            // 学生角色只能为自己退课
            if ("学生".equals(role) || "STUDENT".equals(role)) {
                if (!studentId.equals(relatedId)) {
                    return Result.error("权限不足，只能为自己退课");
                }
            }
            
            boolean success = enrollmentService.dropCourse(studentId, courseId, semester);
            if (success) {
                return Result.success("退课成功");
            } else {
                return Result.error("退课失败，未选择该课程或已有成绩");
            }
        } catch (Exception e) {
            return Result.error("退课失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询学生选课
     */
    @GetMapping("/student/{studentId}")
    public Result<Page<Enrollment>> getStudentEnrollments(
            @PathVariable String studentId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String semester,
            HttpServletRequest request) {
        try {
            // 获取当前用户信息
            String role = (String) request.getAttribute("role");
            String relatedId = (String) request.getAttribute("relatedId");
            
            // 学生角色只能查询自己的选课
            if ("学生".equals(role) || "STUDENT".equals(role)) {
                if (!studentId.equals(relatedId)) {
                    return Result.error("权限不足，只能查询自己的选课");
                }
            }
            
            Pageable pageable = PageRequest.of(page, size);
            Page<Enrollment> enrollments = enrollmentService.getStudentEnrollments(studentId, semester, pageable);
            return Result.success(enrollments);
        } catch (Exception e) {
            return Result.error("查询学生选课失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询课程选课学生
     */
    @GetMapping("/course/{courseId}")
    public Result<Page<Enrollment>> getCourseEnrollments(
            @PathVariable String courseId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String semester) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Enrollment> enrollments = enrollmentService.getCourseEnrollments(courseId, semester, pageable);
            return Result.success(enrollments);
        } catch (Exception e) {
            return Result.error("查询课程选课学生失败：" + e.getMessage());
        }
    }
    
    /**
     * 选课列表查询
     */
    @GetMapping("/list")
    public Result<Page<Map<String, Object>>> getEnrollmentList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String courseId,
            @RequestParam(required = false) String semester,
            @RequestParam(required = false) String status,
            HttpServletRequest request) {
        try {
            // 获取当前用户信息
            String role = (String) request.getAttribute("role");
            String relatedId = (String) request.getAttribute("relatedId");
            
            System.out.println("选课列表查询 - 角色: " + role + ", 关联ID: " + relatedId + ", 原始学号参数: " + studentId);
            
            // 学生角色只能查看自己的选课列表
            if ("学生".equals(role) || "STUDENT".equals(role)) {
                studentId = relatedId; // 强制设置为当前学生的学号
                System.out.println("学生角色权限控制 - 强制设置学号: " + studentId);
            }
            
            System.out.println("最终查询参数 - 学号: " + studentId + ", 课程: " + courseId + ", 学期: " + semester + ", 状态: " + status);
            
            Pageable pageable = PageRequest.of(page, size);
            Page<Map<String, Object>> enrollments = enrollmentService.getEnrollmentListWithDetails(pageable, studentId, courseId, semester, status);
            
            System.out.println("查询结果 - 总记录数: " + enrollments.getTotalElements() + ", 当前页记录数: " + enrollments.getContent().size());
            
            return Result.success(enrollments);
        } catch (Exception e) {
            System.err.println("查询选课列表异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询选课列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 选课统计
     */
    @GetMapping("/statistics")
    public Result<Object> getEnrollmentStatistics(@RequestParam(required = false) String semester) {
        try {
            Object statistics = enrollmentService.getEnrollmentStatistics(semester);
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取选课统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取选课总数
     */
    @GetMapping("/count")
    public Result<Long> getEnrollmentCount() {
        try {
            long count = enrollmentService.getEnrollmentCount();
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("获取选课总数失败：" + e.getMessage());
        }
    }
}
